package firstDay;

/**
 * @author nhp
 * @version 1.0
 * @description TODO
 * @date 2024-05-24 16:24
 */
public class LeetCode707 {

    public static void main(String[] args) {
        MyLinkedList myLinkedList = new MyLinkedList();
        myLinkedList.addAtHead(7);
        myLinkedList.addAtHead(2);
        myLinkedList.addAtHead(1);
        myLinkedList.addAtIndex(3,0);
        myLinkedList.deleteAtIndex(2);
        myLinkedList.addAtHead(6);
        myLinkedList.addAtTail(4);
        myLinkedList.get(4);
        myLinkedList.addAtHead(4);
        myLinkedList.addAtIndex(5,0);
        myLinkedList.addAtHead(6);

    }
}

class MyLinkedList {

    //链表长度
    int size;
    //头节点
    ListNode head;

    public MyLinkedList() {
        this.size = 0;
    }

    public int get(int index) {
        if(size == 0 || index >= size || index < 0){
            return -1;
        }
        int i = 0;
        ListNode cur = head;
        while(true){
            if(i == index){
                return cur.val;
            }
            cur = cur.next;
            i++;
        }
    }

    public void addAtHead(int val) {
        addAtIndex(0,val);
    }

    public void addAtTail(int val) {
        addAtIndex(size,val);
    }

    public void addAtIndex(int index, int val) {
        if(index > size || index < 0){
            return;
        }
        ListNode dump = new ListNode(-1);
        dump.next = head;
        ListNode pre = dump;
        int temp = 0;
        while(true){
            if(temp == index){
                ListNode var =  new ListNode(val);
                if(index == size){
                    pre.next = var;
                }else{
                    var.next = pre.next;
                    pre.next = var;
                }
                size++;
                head = dump.next;
                break;
            }else{
                pre = pre.next;
                temp++;
            }
        }

    }

    public void deleteAtIndex(int index) {
        if(size == 0 || index >= size || index < 0){
            return;
        }
        ListNode dump = new ListNode(-1);
        dump.next = head;
        ListNode cur = dump;
        int i = 0;
        while(true){
            if(i == index){
                cur.next = cur.next.next;
                size--;
                head = dump.next;
                break;
            }
            cur = cur.next;
            i++;
        }
    }
}

class ListNode{
    int val;
    ListNode next;
    public ListNode(int val){
        this.val = val;
    }
}
